from flask import Flask,render_template,request,escape
import geo
import pandas as pd
import json
key = "d3db9101f93fc24ecd64266e51e08f39"

def direction(key, start_address, end_address):
    start = geo.geocode(key,start_address)['geocodes'][0]['location']
    end = geo.geocode(key,end_address)['geocodes'][0]['location']
    results = geo.walk(key,start,end)
    df = pd.json_normalize(results['route']['paths'][0]['steps'])
    return df


def total_distance(df):
    distance = df['distance'].to_list()
    sum_num = 0
    for i in distance:
        sum_num += int(i)
    return sum_num


def total_time(df):
    duration = df['duration'].to_list()
    sum_num = 0
    for i in duration:
        sum_num += int(i)
    return sum_num // 60

app = Flask(__name__)


@app.route('/')
def entry():
	return render_template('entry.html')


def log_request(req:'flask_request',res:str) -> None:
    with open('walk.log','a') as log:
        print(req.form,req.remote_addr,req.user_agent,res,file=log,sep='|')


@app.route('/results',methods=['GET','POST'])
def results() -> 'html':
    key = request.form['key']
    start_address = request.form['start']
    end_address = request.form['end']
    title = '查询结果'
    df = direction(key, start_address, end_address)
    results = df.loc[:, ['instruction', 'distance', 'duration']]
    results.columns = ['指引', '路程', '时间']
    the_distance = total_distance(df)
    the_time = total_time(df)
    route = results['指引'].tolist()
    log_request(request, route)
    return render_template('results.html',
                           the_title=title,
                           the_start_address=start_address,
                           the_end_address=end_address,
                           the_results=results,
                           the_html_table=results.to_html(index=False),
                           the_total_walk=the_distance,
                           the_total_walk_time=the_time, )


@app.route('/viewlog')
def viewlog() -> 'html':
    contents = []
    with open('walk.log','r') as log:
        for line in log:
            contents.append([])
            for item in line.split('|'):
                contents[-1].append(escape(item))
    titles = ["Formdata","Host_url","remote_addr","results"]
    return render_template('viewlog.html',
                           the_title = '日志系统',
                           the_row_titles = titles,
                           the_data = contents,)


if __name__ == '__main__':
    app.run(debug=True)
